import Message from './MessageComponent.vue'
import { create } from '../dom'
import { createApp } from 'vue'

type MessageOptions = {
  space?: string // 消息框间隔
  maxMessage?: number // 最大消息数
}
class MessageManager {
  space: number
  messageList: HTMLElement[]
  maxMessage: number
  rootMessageContainer: HTMLElement
  private elementTimeouts = new WeakMap<HTMLElement, number>()
  constructor(options: MessageOptions = {}) {
    this.space = parseInt(options.space || '16', 10)
    this.messageList = []
    this.maxMessage = options.maxMessage || 5

    this.rootMessageContainer = create('div')
      .addClass('vivid-message-container')
      .styleSheetRule('.vivid-message-container', {
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        height: 'auto',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        zIndex: '3000',
        gap: `${this.space}px`,
        pointerEvents: 'none',
      }).el

    document.body.appendChild(this.rootMessageContainer)
  }

  addMessage(el: HTMLElement, close: () => void, duration = 2000) {
    // 达到最大消息数时移除最早的消息
    if (this.messageList.length >= this.maxMessage) {
      const firstMessage = this.messageList.shift()
      if (firstMessage) {
        this.animateOut(firstMessage, () => firstMessage.remove())
      }
    }

    // 添加动画效果
    el.style.opacity = '0'
    el.style.transform = 'translateY(-20px)'
    el.style.transition = 'all 0.3s ease'

    this.rootMessageContainer.appendChild(el)
    this.messageList.push(el)

    // 下一帧触发动画
    requestAnimationFrame(() => {
      el.style.opacity = '1'
      el.style.transform = 'translateY(0)'
    })

    // 设置自动关闭
    const timeout = setTimeout(() => {
      this.animateOut(el, () => {
        close()
        this.messageList.splice(this.messageList.indexOf(el), 1)
      })
    }, duration)
    this.elementTimeouts.set(el, timeout)
  }

  // 添加出场动画
  animateOut(el: HTMLElement, onComplete: () => void) {
    // 清除之前的超时
    if (this.elementTimeouts.has(el)) {
      clearTimeout(this.elementTimeouts.get(el))
    }

    el.style.opacity = '0'
    el.style.transform = 'translateY(-20px)'

    // 动画完成后移除元素
    const onTransitionEnd = () => {
      el.removeEventListener('transitionend', onTransitionEnd)
      onComplete()
    }

    el.addEventListener('transitionend', onTransitionEnd)
  }
}

const messageManager = new MessageManager({
  space: '16',
  maxMessage: 5,
})

export function message(msg: string, type = 'info', duration = 2000, closeFn = () => {}) {
  const container = create('div').inlineStyle({
    pointerEvents: 'auto',
    transition: 'all 0.3s ease',
  })

  const app = createApp(Message, {
    msg,
    type,
    onClose: () =>
      messageManager.animateOut(container.el, () => {
        app.unmount()
        container.remove()
      }),
  })

  app.mount(container.el)

  // 添加消息
  messageManager.addMessage(
    container.el,
    () => {
      app.unmount()
      container.remove()
    },
    duration,
  )

  // 返回关闭函数
  return () => {
    messageManager.animateOut(container.el, () => {
      app.unmount()
      container.remove()

      // 从消息列表中移除
      const index = messageManager.messageList.indexOf(container.el)
      if (index !== -1) {
        messageManager.messageList.splice(index, 1)
      }
    })
  }
}
